//
//  RELCourseManager.m
//  BaxTer
//
//  Created by wsj2015 on 16/10/30.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "RLMCourseManager.h"
#import "Realm.h"
#import "BTCourseModel.h"
static RLMCourseManager *manager = nil;

@interface RLMCourseManager ()

@property (nonatomic,  strong) RLMRealm *realm;


@end
@implementation RLMCourseManager

- (RLMRealm *)realm{
   
    _realm = [RLMRealm defaultRealm];
    
    return _realm;
}



+ (instancetype)manager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager =[[RLMCourseManager alloc] init];
    });
    
    return manager;
}

- (void)configWithUserAccout:(NSString *)userAccout
{
    NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [docPath objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"BT_%@",userAccout]];
    WSJLog(@"数据库目录 = %@",filePath);
    
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    config.fileURL = [NSURL URLWithString:filePath];
   
    config.readOnly = NO;
    int currentVersion = 1.0;
    config.schemaVersion = currentVersion;
    
    config.migrationBlock = ^(RLMMigration *migration , uint64_t oldSchemaVersion) {
        // 这里是设置数据迁移的block
        if (oldSchemaVersion < currentVersion) {
        }
    };
    
    [RLMRealmConfiguration setDefaultConfiguration:config];
    
}

- (void)creatOrUpdateCourse:(BTCourseModel *)model{
    
    weakSelf_define;
    [self.realm transactionWithBlock:^{
      NSDictionary  *dict =  [model mj_keyValues];
    
      RLMCourse *course =  [RLMCourse createOrUpdateInRealm:weakSelf.realm withValue: dict];
        WSJLog(@"%@",course);
    }];
    
   
}
- (void)deleteCoursesWithCourseArr:(NSArray <BTCourseModel*>*)courseArray doneBlock:(void(^)())doneBlock{
    

//    RLMResults *r = [RLMCourse objectsInRealm:self.realm where:nil];
//    RLMCourse *course = r.lastObject;
    
//    WSJLog(@"%@",course);
    weakSelf_define;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self.realm transactionWithBlock:^{
            [courseArray enumerateObjectsUsingBlock:^(BTCourseModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
              
              
                RLMCourse *course = [RLMCourse objectInRealm:weakSelf.realm forPrimaryKey:obj.id];
                
                @try {
                    if (course) {
                         [weakSelf.realm deleteObject:course];
                    }
                   
                } @catch (NSException *exception) {
                    cwqAlertMessage(@"删除失败,数据库中没有这条数据");
                } @finally {
                    
                }
               
            }];
            
        }];
        dispatch_sync(dispatch_get_main_queue(), ^{
            doneBlock();
        });
        
    });
   

}


- (void)deleteAllObjects{
    
    [self.realm transactionWithBlock:^{
         [self.realm deleteAllObjects];
    }];
   
    
}

- (void)getAllObjectsWithHandel:(void(^)(NSArray <BTCourseModel *>*))handel{
   
    
 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      
        RLMResults *results = [RLMCourse allObjects];
        NSMutableArray *array =[NSMutableArray array];
        for (RLMCourse *course in results) {
            BTCourseModel *model = [BTCourseModel mj_objectWithKeyValues:[course mj_keyValues]];
            [array addObject:model];
        }
        dispatch_sync(dispatch_get_main_queue(), ^{
            handel(array);
        });
        
    });

}



@end
